package net.jeeeyul;

import java.io.IOException;
import java.text.MessageFormat;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;

public class RequestChannelToken extends AbstractChatServlet {
   private static final long serialVersionUID = -4320305915768879056L;

   public void doGet(HttpServletRequest req, HttpServletResponse resp)
         throws IOException {

      ChannelService channelService = ChannelServiceFactory.getChannelService();

      String chatURL = req.getParameter("url");

      String clientId = getClientId(req);
      System.out.println(clientId + "에 대해 토큰 생성");

      PersistenceManager persistenceManager = PMF.get().getPersistenceManager();
      ChatRoom chatRoom = ChatRoom.get(persistenceManager, chatURL);
      chatRoom.addClient(clientId);

      String token = channelService.createChannel(clientId);
      String result = MessageFormat.format("'{' \"token\": \"{0}\" '}'", token);
      resp.setContentType("text/plain");
      resp.getWriter().write(result);
   }

   public static void main(String[] args) {
      String result = MessageFormat
            .format("'{' ''token'': ''{0}'' '}'", "test");
      System.out.println(result);
   }
}
